<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeftOutlined, CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons-vue'
import { getRegistrationDetailApi } from '~/api/common/login'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const detail = ref<Record<string, any> | null>(null)

const MAKEUP_UNIT_MAP: Record<number, string> = {
  1: '跟单信用证基础 (FODC)',
  2: '跟单信用证管理 (MGDC)',
}

function normalizeMakeupUnits(value: unknown): number[] {
  if (Array.isArray(value)) {
    return value
      .map(item => Number(item))
      .filter(num => !Number.isNaN(num))
  }
  if (typeof value === 'number') {
    return Number.isNaN(value) ? [] : [value]
  }
  if (typeof value === 'string') {
    const cleaned = value.replace(/[[\]\s]/g, '')
    if (!cleaned)
      return []
    return cleaned
      .split(',')
      .map(item => Number(item))
      .filter(num => !Number.isNaN(num))
  }
  return []
}

const examUnitLabel = computed(() => {
  const examUnit = detail.value?.exam_subject?.exam_unit
  if (examUnit === null || examUnit === undefined || examUnit === '') {
    return '补考单元'
  }
  return '考试单元'
})

const examUnitText = computed(() => {
  const examUnit = detail.value?.exam_subject?.exam_unit
  if (examUnit !== null && examUnit !== undefined && examUnit !== '') {
    return examUnit
  }
  const units = normalizeMakeupUnits(detail.value?.makeup_unit)
  if (!units.length)
    return '--'
  const mapped = units
    .map(unit => MAKEUP_UNIT_MAP[unit])
    .filter(Boolean)
  return mapped.length ? mapped.join(', ') : '--'
})

function goBack() {
  router.back()
}

// 状态与显示映射
// 报名成功的状态：4, 5, 6
const successStatusSet = new Set([4, 5, 6])

function isSuccessStatus(status: number | null | undefined) {
  return typeof status === 'number' && successStatusSet.has(status)
}

function getRegistrationStatusText(status: number | null | undefined) {
  // 根据8个状态定义显示报名状态
  switch (status) {
    case 0: return '信息待完善'
    case 1: return '待缴费'
    case 2: return '已缴费待审核'
    case 3: return '已缴费待审核'
    case 4: return '报名成功'
    case 5: return '报名成功'
    case 6: return '报名成功'
    case 7: return '缴费失败'
    case 8: return '缴费失败'
    default: return '--'
  }
}

function getRegistrationStatusColor(status: number | null | undefined) {
  const text = getRegistrationStatusText(status)
  if (text === '缴费失败')
    return '#ff4d4f'
  if (text === '--')
    return '#999'
  return '#376d9b'
}

function getPayStatusText(status: number | null | undefined) {
  // 根据8个状态定义显示支付状态
  if (status === 0)
    return '--'
  if (status === 1)
    return '待缴费'
  if (status === 2)
    return '已缴费待审核'
  if (status === 3)
    return '已缴费待审核'
  if (status === 4)
    return '报名成功'
  if (status === 5)
    return '报名成功'
  if (status === 6)
    return '报名成功'
  if (status === 7)
    return '缴费失败'
  if (status === 8)
    return '缴费失败'
  return '--'
}

function getGenderText(gender: number | null | undefined) {
  if (gender === 1)
    return '男'
  if (gender === 2)
    return '女'
  return '-'
}
function getGenderEnText(genderEn: string | null | undefined) {
  if (genderEn === 'male')
    return 'Male'
  if (genderEn === 'female')
    return 'Female'
  return genderEn || '-'
}

function getFullAddress() {
  if (!detail.value)
    return '-'
  const { address } = detail.value
  return address || '-'
}

function getInvoiceTypeText(type: number | null | undefined) {
  if (type === 1)
    return '增值税专用发票'
  if (type === 2)
    return '增值税普通发票'
  return '--'
}

function getInvoiceStatusText(status: number | null | undefined) {
  const registrationStatus = status
  
  // 状态 0: 信息待完善 - 无发票
  if (registrationStatus === 0)
    return '--'
  
  // 状态 1: 待缴费 - 无发票
  if (registrationStatus === 1)
    return '--'
  
  // 状态 2: 缴费待审核 - 未申请发票
  if (registrationStatus === 2)
    return '--'
  
  // 状态 3: 缴费待审核（已申请开发票）- 等待处理
  if (registrationStatus === 3)
    return '等待处理'
  
  // 状态 4: 已经缴费成功（不申请发票）- 无发票
  if (registrationStatus === 4)
    return '--'
  
  // 状态 5: 已经缴费成功（申请发票 发票审核中状态）- 等待处理
  if (registrationStatus === 5)
    return '等待处理'
  
  // 状态 6: 已经缴费成功（申请发票 发票已经开的状态）- 已开票
  if (registrationStatus === 6)
    return '已开票'
  
  // 状态 7: 缴费审核拒绝（未申请开发票状态）- 无发票
  if (registrationStatus === 7)
    return '--'
  
  // 状态 8: 缴费审核被拒绝（已申请开发票状态 发票未开票失败）- 开票失败
  if (registrationStatus === 8)
    return '开票失败'
  
  // 默认情况
  return '--'
}

function getInvoiceStatusColor(status: number | null | undefined) {
  const registrationStatus = status
  
  // 状态 6: 已开票，绿色
  if (registrationStatus === 6)
    return '#52c41a'
  
  // 状态 8: 开票失败，红色
  if (registrationStatus === 8)
    return '#ff4d4f'
  
  // 状态 3, 5: 等待处理，黄色
  if (registrationStatus === 3 || registrationStatus === 5)
    return '#faad14'
  
  // 其他状态，灰色
  return '#8c8c8c'
}

function getInvoiceStatusType(status: number | null | undefined): 'not-issued' | 'processing' | 'issued' | 'failed' | 'none' {
  const registrationStatus = status
  
  // 状态 6: 已开票
  if (registrationStatus === 6)
    return 'issued'
  
  // 状态 8: 开票失败
  if (registrationStatus === 8)
    return 'failed'
  
  // 状态 3, 5: 等待处理
  if (registrationStatus === 3 || registrationStatus === 5)
    return 'processing'
  
  // 其他状态
  return 'none'
}

function formatMoney(amount: string | number | null | undefined) {
  const n = typeof amount === 'string' ? Number(amount) : (amount ?? 0)
  if (Number.isNaN(n))
    return '-'
  return n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

// 处理缴费凭证图片URL（支持多个URL用逗号分隔）
function getPaymentProofImages(paymentProof: string | null | undefined): string[] {
  if (!paymentProof)
    return []
  // 按逗号分割，过滤空字符串
  return paymentProof.split(',').filter(url => url && url.trim())
}

// 详情页配色主题
const detailTheme = 'theme-emerald'
// const detailTheme = ref<'theme-slate' | 'theme-emerald' | 'theme-orange' | 'theme-slate'>('theme-blue')

onMounted(async () => {
  // 兼容多种参数：orderId | registrationId | id
  const id
    = (route.query.orderId as string)
      || (route.query.registrationId as string)
      || (route.query.id as string)
      || ''
  if (!id)
    return
  loading.value = true
  try {
    const resp = await getRegistrationDetailApi(String(id)) as any
    if (resp?.code === 0 && resp?.data) {
      detail.value = resp.data
    }
  }
  finally {
    loading.value = false
  }
})
</script>

<template>
  <page-container>
    <div
      class="detail-card"
      :class="detailTheme"
      style="

    "
    >
      <div class="detail-header">
        <span
          style="flex: 1;
        position:relative;
        top:15px;
        left:10px;font-size: 17px;
        font-weight: 600; color: #333;"
        >
          {{ '报名详情' }}</span>
        <div
          class="back-button"
          style="
          position:relative;
        top:15px;
        left:-5px;font-size: 17px;
              color: #376d9b;
              padding: 0;
              height: auto;
              display: flex;
              align-items: center;
              cursor: pointer;

            "
          @click="goBack"
        >
          <ArrowLeftOutlined style="font-size: 18px; margin-right: 4px;" />
          <span
            style="
            font-size: 16px;"
          >返回</span>
        </div>
      </div>

      <div
        style="
      overflow-y: scroll;
      position: relative;
      top:-40px;
      margin: 0 0% ;
      padding: 0px 10%;
      max-height: 83vh;
      padding-bottom: 80px;
      margin-bottom: 40px;
      "
      >
        <!-- 科目信息 -->
        <a-card :bordered="false" class="info-card">
          <a-descriptions title="科目信息" :column="3" size="middle" class="desc">
            <a-descriptions-item label="考试科目" :span="1">
              {{ detail?.exam_subject?.subject_name || '--' }}
            </a-descriptions-item>
            <a-descriptions-item label="报名时间">
              {{ detail?.registration_time || '--' }}
            </a-descriptions-item>
            <a-descriptions-item label="考试类别">
              {{ detail?.exam_subject?.exam_class || '--' }}
            </a-descriptions-item>
            <a-descriptions-item :label="examUnitLabel" :span="1">
              {{ examUnitText }}
            </a-descriptions-item>
            <a-descriptions-item label="状态" :span="1">
              <span
                :style="{
                  fontSize: '18px',
                  position: 'relative',
                  top: '-1px',
                  display: 'inline-flex',
                  alignItems: 'center',
                  color: getRegistrationStatusColor(detail?.registration_status),
                }"
              >
                <CheckCircleOutlined
                  v-if="isSuccessStatus(detail?.registration_status)"
                  style="margin-right: 6px; color: #52c41a;"
                />
                {{ getRegistrationStatusText(detail?.registration_status) }}
              </span>
            </a-descriptions-item>
          </a-descriptions>
        </a-card>

        <a-card :loading="loading" class="info-card" :bordered="false">
          <a-descriptions
            :column="3"
            title="基本信息"
            size="middle"
            class="desc"
          >
            <a-descriptions-item label="姓名">
              {{ detail?.username || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="性别">
              {{ getGenderText(detail?.gender) }}
            </a-descriptions-item>
            <a-descriptions-item label="出生日期">
              {{ detail?.birth_date || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="手机号码">
              {{ detail?.phone || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="联系地址" :span="2">
              {{ getFullAddress() }}
            </a-descriptions-item>
            <a-descriptions-item label="工作单位" :span="3">
              {{ detail?.company_name || '-' }}
            </a-descriptions-item>
          </a-descriptions>

          <a-descriptions
            title="LIBF 信息"
            :column="3"
            size="middle"
            class="desc"
          >
            <a-descriptions-item label="Family Name">
              {{ detail?.family_name || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="Given Name">
              {{ detail?.given_name || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="Gender">
              {{ getGenderEnText(detail?.gender_en) }}
            </a-descriptions-item>
            <a-descriptions-item label="Title">
              {{ detail?.title_en || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="Birth Date">
              {{ detail?.birth_date_en || detail?.birth_date || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="Email">
              {{ detail?.email || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="Company">
              {{ detail?.company_name_en || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="Address" :span="2">
              {{ detail?.address_en || '-' }}
            </a-descriptions-item>
          </a-descriptions>
        </a-card>

        <!-- 缴费信息 -->
        <a-card :bordered="false" class="info-card">
          <a-descriptions title="缴费信息" :column="3" size="middle" class="desc">
            <a-descriptions-item label="考试费用">
              {{ formatMoney(detail?.exam_fee) }} 元
            </a-descriptions-item>
            <a-descriptions-item label="支付状态">
              <span
                :style="{
                  color: getRegistrationStatusColor(detail?.registration_status),
                  fontSize: '17px',
                }"
              >
                {{ getPayStatusText(detail?.registration_status) }}
              </span>
            </a-descriptions-item>
            <a-descriptions-item label="支付时间">
              {{ detail?.payment_time || '--' }}
            </a-descriptions-item>
            <a-descriptions-item v-if="detail?.payment_proof" label="缴费凭证" :span="1">
              <div class="payment-proof-images">
                <a-image
                  v-for="(imageUrl, index) in getPaymentProofImages(detail?.payment_proof)"
                  :key="index"
                  :src="imageUrl.trim()"
                  :width="80"
                  :height="80"
                  :preview="true"
                  class="payment-proof-thumbnail"
                />
              </div>
            </a-descriptions-item>
          </a-descriptions>
        </a-card>

        <!-- 发票信息 -->
        <a-card :bordered="false" class="info-card">
          <a-descriptions title="发票信息" :column="3" size="middle" class="desc">
            <a-descriptions-item label="发票状态">
              <span
                :style="{
                  color: getInvoiceStatusColor(detail?.registration_status),
                  fontSize: '17px',
                  display: 'inline-flex',
                  alignItems: 'center',
                }"
              >
                <CheckCircleOutlined
                  v-if="getInvoiceStatusType(detail?.registration_status) === 'issued'"
                  style="margin-right: 6px; color: #52c41a;"
                />
                <CloseCircleOutlined
                  v-else-if="getInvoiceStatusType(detail?.registration_status) === 'failed'"
                  style="margin-right: 6px; color: #ff4d4f;"
                />
                {{ getInvoiceStatusText(detail?.registration_status) }}
              </span>
            </a-descriptions-item>
            <a-descriptions-item label="发票类型">
              {{ getInvoiceTypeText(detail?.invoice_type) }}
            </a-descriptions-item>
            <a-descriptions-item label="发票抬头" :span="2">
              {{ detail?.invoice_title || '--' }}
            </a-descriptions-item>
            <a-descriptions-item label="发票内容">
              {{ `${detail?.exam_subject?.exam_class}考试费` || '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="纳税人识别号" :span="2">
              {{ detail?.taxpayer_id || '--' }}
            </a-descriptions-item>
            <a-descriptions-item label="发票开具时间">
              {{ detail?.invoice_issue_time === 0 ? '当年'
                : detail?.invoice_issue_time === 1 ? '次年'
                  : '--' }}
            </a-descriptions-item>
          </a-descriptions>
        </a-card>

        <!-- 其它信息 -->
        <a-card :bordered="false" class="info-card">
          <a-descriptions title="考务信息" :column="3" size="middle" class="desc">
            <a-descriptions-item label="是否参加考前培训">
              {{ detail?.pre_exam_training === 1 ? '是' : detail?.pre_exam_training === 2 ? '否' : '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="成绩">
              {{ detail?.exam_score ?? '--' }}
            </a-descriptions-item>
            <a-descriptions-item label="成绩状态">
              {{ detail?.score_status === 1 ? '已出分' : '未出分' }}
            </a-descriptions-item>
          </a-descriptions>
        </a-card>
      </div>
    </div>
  </page-container>
</template>

<style scoped>
.detail-card {
  max-height: 100vh;
  margin: 0 auto;
}
.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
  top:-40px;
  padding: 12px 0 20px;
  border-bottom: 1px solid #eaeaea;
  margin-bottom: 20px;
}
.back {
  display: inline-flex;
  align-items: center;
  cursor: pointer;
  color: #333;
}
.title {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}
.title .sub {
  font-size: 17px;
  color: #8a8a8a;
  margin-left: 8px;
  font-weight: 400;
}
.info-card {
  margin-bottom: 20px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 10px 30px -15px rgba(32, 81, 134, 0.25);
}
.info-card:last-of-type {
  margin-bottom: 0;
}
.info-card :deep(.ant-card-body) {
  padding: 20px 24px;
}
.desc :deep(.ant-descriptions-header) {
  margin-bottom: 12px;
}
.desc :deep(.ant-descriptions-title) {
  font-size: 18px;
  font-weight: 600;
  color: #1f1f1f;
}
.detail-card :deep(.ant-card-head-title) {
  font-weight: 600;
}
.desc :deep(.ant-descriptions-item-label) {
  color: #6b7280;
  font-size: 15px;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Microsoft YaHei', 'Hiragino Sans GB', 'WenQuanYi Micro Hei', Arial, 'SimSun', 'sans-serif';
}
.desc :deep(.ant-descriptions-item-content) {
  font-size: 17px;
}
.badge {
  display: inline-block;
  padding: 3px 10px;
  border-radius: 12px;
  font-size: 18px;
  border: 1px solid rgba(0,0,0,0.05);
  background: #f5f5f5;
  color: #666;
}
.badge-primary {
  background: #e6f4ff;
  color: #1677ff;
  border-color: #bae0ff;
}
.badge-orange {
  background: #fff7e6;
  color: #fa8c16;
  border-color: #ffd591;
}
.badge-blue {
  background: #e6f4ff;
  color: #1677ff;
  border-color: #bae0ff;
}
.badge-green {
  background: #f6ffed;
  color: #1a80c4;
  border-color: #8fceeb;
}
.badge-gray {
  background: #f5f5f5;
  color: #666;
  border-color: #d9d9d9;
}
.badge-red {
  background: #fff1f0;
  color: #f5222d;
  border-color: #ffa39e;
}
div::-webkit-scrollbar {
  width: 5px; /* 滚动条宽度 */
}
div::-webkit-scrollbar-thumb {
  background-color: rgba(127, 154, 194, 0.5); /* 半透明黑色，你可以根据需要调整透明度 */
  border-radius: 4pxrgba(150, 166, 190, 0.5)
}
/* 滑动的更细更透明 */

/* ===== 主题配色 ===== */
/* 1) 蓝色（与当前列表按钮蓝系协调） */
.theme-blue .detail-header {
  border-bottom-color: #e6eef7;
}
.theme-blue :deep(.ant-descriptions-title) {
  color: #1f3b57;
}
.theme-blue .badge-primary {
  background: #e6f0ff;
  color: #376d9b;
  border-color: #b7d0f0;
}
.theme-blue .info-card {
  box-shadow: 0 10px 30px -15px rgba(55, 109, 155, 0.28);
}
.theme-blue :deep(.ant-card) {
  border-radius: 12px;
}
.theme-blue :deep(.ant-descriptions-item-label) {
  color: #5b7086;
}

/* 2) 蓝绿（清新、偏学院） */
.theme-emerald .detail-header {
  border-bottom-color: #e4e3e3;
}
.theme-emerald :deep(.ant-descriptions-title) {
  color: rgb(28, 68, 107);
}
.theme-emerald .badge-primary {
  background: #ecfdf5;
  color: rgb(93, 184, 128);
  border-color: rgb(78, 187, 74);
}
.theme-emerald .info-card {
  box-shadow: 0 10px 30px -15px rgba(11, 70, 124, 0.25);
}
.theme-emerald :deep(.ant-descriptions-item-label) {
  color: rgb(24, 79, 110);
  position:relative;
  top:2px;
}

/* 3) 橙色（活力、强调状态） */
.theme-orange .detail-header {
  border-bottom-color: #ffe8d2;
}
.theme-orange :deep(.ant-descriptions-title) {
  color: #9a3412;
}
.theme-orange .badge-primary {
  background: #fff7e6;
  color: #f59e0b;
  border-color: #ffd591;
}
.theme-orange .info-card {
  box-shadow: 0 10px 30px -15px rgba(245, 158, 11, 0.25);
}
.theme-orange :deep(.ant-descriptions-item-label) {
  color: #a16207;
}

/* 4) 石板灰（低饱和、商务风） */
.theme-slate .detail-header {
  border-bottom-color: #e5e7eb;
}
.theme-slate :deep(.ant-descriptions-title) {
  color: #111827;
}
.theme-slate .badge-primary {
  background: #f3f4f6;
  color: #374151;
  border-color: #e5e7eb;
}
.theme-slate .info-card {
  box-shadow: 0 10px 30px -15px rgba(55, 65, 81, 0.22);
}
.theme-slate :deep(.ant-descriptions-item-label) {
  color: #6b7280;
}

/* 缴费凭证图片展示样式 */
.payment-proof-images {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.payment-proof-thumbnail {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.payment-proof-thumbnail:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
  transform: translateY(-2px);
}

.payment-proof-thumbnail :deep(.ant-image-img) {
  object-fit: cover;
  display: block;
}

@media (max-height: 800px) {
  .detail-card > div[style*="overflow-y"] {
    max-height: calc(100vh - 120px) !important;
    padding-bottom: 60px !important;
    margin-bottom: 30px !important;
  }
}
</style>
